const request = require('request');
const fs = require('fs');
const path = require('path');

const BingAudio = function (json, url, audioDir) {
  this.json = json;
  this.url = url;
  this.audioDir = audioDir;
}

BingAudio.prototype.crawl = function () {
  for (const v of this.json) {
    this._writeBingAudio(v.English, v);
  }
}

BingAudio.prototype.crawlZh = function () {
  for (const v of this.json) {
    this._writeBingAudio(v.Chinese, v);
  }
}

BingAudio.prototype._writeBingAudio = function (word, obj) {
  // 判断音频是否已经存在
  const audioPath = path.join(this.audioDir, `${obj.English}.mp3`);
  if (fs.existsSync(audioPath)) {
    return;
  }

  // 获取音频文件，成功则写到文件
  const audio = request
    .get(`${this.url}${encodeURI(word)}`)
    .on('response', function (response) {
      if (response.statusCode === 200) {
        audio.pipe(fs.createWriteStream(audioPath));
      } else {
        console.log(word, response.statusCode);
      }
    })
    .on('error', function (error) {
      console.log(word);
      console.log(error);
    })
}

module.exports = BingAudio